package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.iba.model.dto.SaveObjIBADTO;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.dto.constraint.IbaDTO;
import com.ty.basic.entity.CTyEntityBaseDO;
import cqrtplm.common.CommonService;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.mapper.RTPlanPublishMapper;
import cqrtplm.service.RTPlanPublishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class RTPlanPublishServiceImpl implements RTPlanPublishService {

    private static final String status1="编制中";
    private static final String status2="正常";

    @Resource
    private RTPlanPublishMapper rtPlanPublishMapper;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private CommonService commonService;

    @Value("${ipd.base.url:http://127.0.0.1:9588}")
    private String ipdUrl;

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void planPublish(String workFlowContainerId) throws IOException{
        BigInteger prj = rtPlanPublishMapper.selectPrjById(workFlowContainerId);
        if (prj == null) {
            return;
        }
        List<SaveObjIBADTO> objWithIbaList = new ArrayList<>();
        List<BigInteger> JobId = rtPlanPublishMapper.selectJobById(prj);
        String prjState=rtPlanPublishMapper.selectPrjIba(prj);

        if (StringUtils.isNotBlank(prjState)&& StringUtils.equals(prjState,status1)) {
            CTyEntityBaseDO entityBase = new CTyEntityBaseDO(prj,
                                                             TableTypeConstrant.TY_PROJECT_TYPE);
            IbaDTO ibaDTO = createIbaDto("ExecutionStatus", "正常");
            SaveObjIBADTO saveObjDto = createSaveObjDto(entityBase, ibaDTO);
            objWithIbaList.add(saveObjDto);
            if (CollUtil.isNotEmpty(JobId)) {
                for (BigInteger oid : JobId) {
                    CTyEntityBaseDO job = new CTyEntityBaseDO(oid,
                                                              TableTypeConstrant.TY_JOB_OTYPE);
                    IbaDTO iba = createIbaDto("ExecutionStatus", "正常");
                    SaveObjIBADTO jobDto = createSaveObjDto(job, iba);
                    objWithIbaList.add(jobDto);
                }
            }
        }else {
            throw RTErrorCodeEnum.PRJ_STATE_ERROR.getException("当前项目状态非编制中，无法发布");
        }

//        if (StringUtils.isNotBlank(prjState)&& StringUtils.equals(prjState,status2)){
//            Map<String, List<AttributeVO>> ibaMaps = typlmAttributeValueService.getIbaAttrValueByOidAndKeys(
//                    JobId,
//                    TableTypeConstrant.TY_JOB_OTYPE,
//                    Collections.singletonList("ExecutionStatus"));
//            List<BigInteger> inEditingPlanOids = new ArrayList<>();
//            for (BigInteger oid : JobId) {
//                String oidStr = oid.toString();
//                List<AttributeVO> attrs = ibaMaps.get(oidStr);
//                // 只有当属性存在且值为"编制中"时才加入集合
//                if (CollUtil.isNotEmpty(attrs)) {
//                    AttributeVO attr = attrs.get(0);
//                    String value = attr.getAttributeValue();
//                    if (status1.equals(value)) {
//                        inEditingPlanOids.add(oid);
//                    }
//                }
//            }
//            if (CollUtil.isNotEmpty(inEditingPlanOids)) {
//                for (BigInteger planOid : inEditingPlanOids) {
//                    CTyEntityBaseDO job = new CTyEntityBaseDO(planOid,
//                                                              TableTypeConstrant.TY_JOB_OTYPE);
//                    IbaDTO iba = createIbaDto("ExecutionStatus", "正常");
//                    SaveObjIBADTO jobDto = createSaveObjDto(job, iba);
//                    objWithIbaList.add(jobDto);
//                }
//                //发布临时任务
//                rtPlanPublishMapper.updateJobPublish(inEditingPlanOids);
//
//            }
//        }

        executeHttp(prj);
        updateIba(objWithIbaList);
    }

//    @Transactional(rollbackFor = Exception.class)
    public void updateIba(List<SaveObjIBADTO> objWithIbaList) {
        // 批量保存IBA属性
        if (CollUtil.isNotEmpty(objWithIbaList)) {
            log.info("============开始修改IBA属性===================>>");
            typlmAttributeValueService.batchSaveIBAByObjList(objWithIbaList, false);
        }
    }

    private void executeHttp(BigInteger prj) throws IOException {
        //更新项目状态
        log.info("============开始更新项目状态===================>>");
        updateProjectState(prj);
        log.info("============开始更新项目状态完成===================>>");
        //获取计划并发布
        log.info("============开始获取计划===================>>");
        JSONObject plan = getProjectPlan(prj);
        log.info("============开始获取计划完成===================>>");
        log.info("============开始发布计划===================>>:{}", plan);
        if (ObjectUtil.isNotEmpty(plan)) {
            assert plan != null;
            JSONObject data = plan.getJSONObject("data");
            publishProjectPlan(data, prj);
            log.info("============开始发布计划完成===================>>");
        }else {
            throw RTErrorCodeEnum.PRJ_STATE_ERROR.getException("计划为空 无法发布");
        }

    }

    private void updateProjectState(BigInteger prj) throws IOException {
        String url = ipdUrl + "/api/v1/project/setProjectStateStarted";
        JSONObject data = new JSONObject();
        data.put("input", Collections.singletonList(String.valueOf(prj)));
        String responseData = commonService.sendPostRequestToIPD(url, data.toJSONString());
        log.info("============开始更新项目状态完成,执行结果===================>>:{}", responseData);
    }

    private JSONObject getProjectPlan(BigInteger prj) throws IOException{
        String url = ipdUrl + "/api/v1/plan/queryPlanByParent";
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("parentOID", prj)
                .queryParam("parentOTYPE", TableTypeConstrant.TY_PROJECT_TYPE);
        String data = commonService.sendGetRequestToIPD(builder.toUriString());
        return JSONObject.parseObject(data);
    }

    private void publishProjectPlan(JSONObject plan, BigInteger prj) throws  IOException{
        JSONObject param = new JSONObject();
        param.put("changeType", "PUBLISH");
        param.put("planoid", plan.getString("oid"));
        param.put("planotype", plan.getString("otype"));
        param.put("projectoid", prj.toString());
        param.put("projectotype", TableTypeConstrant.TY_PROJECT_TYPE);
        param.put("refoid", plan.getString("oid"));
        param.put("refotype", plan.getString("otype"));
        JSONObject data = new JSONObject();
        data.put("params", param);
        String url = ipdUrl + "/api/v1/project/directlyPublishPlan";
        String result = commonService.sendPostRequestToIPD(url, data.toJSONString());
        log.info("============开始发布计划完成,执行结果===================>>:{}", result);
    }

    // 创建IBA DTO (复用原有逻辑)
    private IbaDTO createIbaDto(String attrKey, String attrValue) {
        IbaDTO ibaDTO = new IbaDTO();
        ibaDTO.setKey(attrKey);
        ibaDTO.setValue(attrValue);
        return ibaDTO;
    }

    // 创建保存对象的DTO (复用原有逻辑)
    private SaveObjIBADTO createSaveObjDto(CTyEntityBaseDO entityBase, IbaDTO ibaDTO) {
        SaveObjIBADTO saveObjDto = new SaveObjIBADTO();
        saveObjDto.setCTyEntityBaseDO(entityBase);
        saveObjDto.setObjIbaList(Collections.singletonList(ibaDTO));
        return saveObjDto;
    }

    public void updatePlanExecutionStatus(String workFlowContainerId) {

    }
}
